package com.net.okhttphelper.upload;

import android.os.Handler;
import android.os.Looper;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 监听上传进度
 * @author jie
 */
public class ProgressRequestBody extends RequestBody {

    private final RequestBody requestBody;
    private final UploadListener uploadListener;
    /**
     * 主线程handler
     */
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public ProgressRequestBody(RequestBody requestBody, UploadListener uploadListener){
        this.requestBody = requestBody;
        this.uploadListener = uploadListener;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }

    @Override
    public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {
        BufferedSink sink = Okio.buffer(sink(bufferedSink));
        requestBody.writeTo(sink);
        sink.flush();
    }

    private Sink sink(Sink bufferedSink) {
        return new ForwardingSink(bufferedSink){
            // 当前写入字节数
            long writeLength = 0L;
            // 总字节长度
            long contentLength = 0L;
            @Override
            public void write(@NotNull Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if (contentLength == 0){
                    contentLength = contentLength();
                }
                writeLength += byteCount;
                if (uploadListener != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            uploadListener.progress(writeLength, contentLength);
                        }
                    });
                }
            }
        };
    }
}
